package soft.quicknote.activity;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import soft.quicknote.DBHelper;
import soft.quicknote.Operation;
import soft.quicknote.R;
import soft.quicknote.adapter.NoteAdapter;
import soft.quicknote.beans.Note;

public class MainActivity extends AppCompatActivity {
    private final static String TAG = MainActivity.class.getSimpleName();

    NoteAdapter adapter;
    DBHelper helper = new DBHelper(this);
    Switch aSwitch;
    private DownloadManager dm;
    private static final int SAVE_FFILE_REQ_CODE = 12385;
    private int savingNoteId = -1;
    private boolean hasEnteredPassword = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main_show);

        setTitle(R.string.app_name);

        adapter = new NoteAdapter(this, new ArrayList<Note>());

        ListView listView = (ListView) findViewById(R.id.note_list);
        registerForContextMenu(listView);

        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Note note = MainActivity.this.adapter.getItem(position);
                startEditActivity(note.getId());
            }
        });
        // 往 adapter 添加获取到的便签
        adapter.addAll(helper.queryAllNotes());
        adapter.notifyDataSetChanged();

    }


    @Override
    public void onResume() {
        super.onResume();
        updateListView();
    }

    void startEditActivity(int noteId) {
        Intent intent = new Intent(this, NoteEditor.class);
        intent.putExtra("op", Operation.EDIT);
        intent.putExtra("id", noteId);
        startActivity(intent);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case R.id.menu_item_add:
                Intent intent = new Intent(this, NoteEditor.class);
                intent.putExtra("op", Operation.CREATE);
                startActivity(intent);
                return true;
//            case R.id.menu_item_download_file:
//                return true;
            case R.id.menu_item_setting:
                startActivity(new Intent(this, SettingActivity.class));
                return true;
            case R.id.show_encrypted_note_switch:
                return true;
            case R.id.menu_item_app_bar_search:
                startActivity(new Intent(this, SearchActivity.class));
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);

        final MenuItem item = menu.findItem(R.id.show_encrypted_note_switch);
        RelativeLayout layout = (RelativeLayout) item.getActionView();
        aSwitch = (Switch) layout.getChildAt(0);
        aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (hasEnteredPassword) {
                    updateListView(isChecked);
                } else if (isChecked) {
                    aSwitch.setChecked(false);
                    trySwitchToEncryptSpace();
                } else {
                    updateListView(false);
                }
            }
        });


        return super.onCreateOptionsMenu(menu);
    }

    private void trySwitchToEncryptSpace() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请输入密码 ！");
        LayoutInflater inflater = getLayoutInflater();
        final View view = inflater.inflate(R.layout.password_input, null);
        builder.setView(view);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String pwd = ((EditText) view.findViewById(R.id.dialog_password)).getText().toString();
                String curPwd = getSharedPreferences("quicknote", MODE_PRIVATE).getString("password", "");
                if (pwd.equals(curPwd)) {
                    hasEnteredPassword = true;
                    aSwitch.setChecked(true);
                } else {
                    Toast.makeText(MainActivity.this, "密码错误！", Toast.LENGTH_LONG).show();
                    aSwitch.setChecked(false);
                }
                dialog.dismiss();
            }
        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();

    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        if (v.getId() == R.id.note_list) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.menu_context_note_list, menu);

            ListView mListView = (ListView) v;

            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;

            Note note = adapter.getItem(info.position);

            menu.findItem(R.id.menu_item_decrypt_note).setVisible(note.getTag() != 0);
            menu.findItem(R.id.menu_item_encrypt_note).setVisible(note.getTag() == 0);
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        Note note = adapter.getItem(info.position);
        switch (item.getItemId()) {
            case R.id.menu_item_encrypt_note:
                setTagForNote(note, 1);
                return true;
            case R.id.menu_item_decrypt_note:
                setTagForNote(note, 0);
                return true;
//            case R.id.menu_item_download_file:
//                savingNoteId = adapter.getItem(info.position).getId();
//                saveFile(adapter.getItem(info.position).getTitle() + ".txt");
//                break;
            case R.id.menu_item_delete_note:
                int id = adapter.getItem(info.position).getId();
                helper.deleteNote(id);
                Log.d(TAG, "删除 Note:" + id);
                updateListView();
                return true;
            case R.id.menu_item_share:
                note = adapter.getItem(info.position);
                shareNote(note);
                return true;
        }
        return super.onContextItemSelected(item);
    }

    void setTagForNote(Note note, int tag) {
        note.setTag(tag);
        helper.saveNote(note);
        updateListView();
    }

    void updateListView() {
        this.updateListView(aSwitch == null ? false : aSwitch.isChecked());
    }

    // 更新便签
    void updateListView(boolean showEncrypted) {
        List<Note> notes = new ArrayList<>();
        for (Note note : helper.queryAllNotes()) {
            if (note.getTag() == (showEncrypted ? 1 : 0)) {
                notes.add(note);
            }
        }
        adapter.clear();
        adapter.addAll(notes);
        adapter.notifyDataSetChanged();
    }

    void filterListView(String keyword) {

    }

    void showDeleteConfirmDialog(final int position) {
        new AlertDialog.Builder(this)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .setTitle("删除便签")
                .setMessage("你确定要删除这条便签？")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        helper.deleteNote(adapter.getItem(position).getId());
                        updateListView();
                    }

                })
                .setNegativeButton("否", null)
                .show();
    }

    void saveFile(String filename) {
        Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("text/plain"); //not needed, but maybe usefull
        intent.putExtra(Intent.EXTRA_TITLE, filename); //not needed, but maybe usefull
        startActivityForResult(intent, SAVE_FFILE_REQ_CODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == SAVE_FFILE_REQ_CODE && resultCode == Activity.RESULT_OK) {
            Uri uri = data.getData();
            Note note = helper.getNoteById(savingNoteId);
            try {
                OutputStream output = getBaseContext().getContentResolver().openOutputStream(uri);
                output.write(note.getContent().getBytes());
                output.flush();
                output.close();
                Toast.makeText(this, "Done", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                Toast.makeText(this, "Error", Toast.LENGTH_SHORT).show();
            }
            savingNoteId = -1;
        }
    }

    void shareNote(Note note) {
        String shareBody = note.getContent().replace("<br>","\n");
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("text/plain");
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "分享：" + note.getTitle());
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
        startActivity(Intent.createChooser(sharingIntent, "分享到"));
    }
}


